#include <jni.h>
#include <string>
#include "LocalSocketClient.cpp"
#include "LocalSocketService.cpp"

LocalSocketClient _client;
LocalSocketService _service;

extern "C"
JNIEXPORT jboolean JNICALL
Java_com_hhw_localsocketsample_MainActivity_startService(JNIEnv *env, jobject thiz,
                                                         jstring address) {
    const char* addr = env->GetStringUTFChars(address,NULL);
    _service.doAccept(addr);
    return 0;
}

extern "C"
JNIEXPORT jboolean JNICALL
Java_com_hhw_localsocketsample_MainActivity_startClient(JNIEnv *env, jobject thiz,
                                                        jstring address) {
    const char* addr = env->GetStringUTFChars(address,NULL);
    return _client.doConnect(addr) == 0;
}

extern "C"
JNIEXPORT void JNICALL
Java_com_hhw_localsocketsample_MainActivity_ClientSend(JNIEnv *env, jobject thiz, jbyteArray data) {

    if (_client.isClose()){
        return;
    }

    long len = env->GetArrayLength(data);//获取源数组长度

    char cs[len+1];//因为是字符串，故而申明的字符长度需要比源数据长度大1，因为要预留最后一个字节0x00收尾
    memset(cs,0,len+1);
    env->GetByteArrayRegion(data, 0, len, (jbyte *)cs);//赋值到cs
    cs[len] = 0;

    _client.send(cs);
}

extern "C"
JNIEXPORT void JNICALL
Java_com_hhw_localsocketsample_MainActivity_ServiceSend(JNIEnv *env, jobject thiz, jbyteArray data) {
    if (_service.isClose()){
        return;
    }

    long len = env->GetArrayLength(data);//获取源数组长度

    char cs[len+1];//因为是字符串，故而申明的字符长度需要比源数据长度大1，因为要预留最后一个字节0x00收尾
    memset(cs,0,len+1);
    env->GetByteArrayRegion(data, 0, len, (jbyte *)cs);//赋值到cs
    cs[len] = 0;

    _service.send(cs);
}